package com.eastmelon.blog.web;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import com.eastmelon.basic.model.SystemContext;

public class SystemContextFilter implements Filter {
	private Integer pageSize;

	@Override
	public void destroy() {

	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
			throws IOException, ServletException {
		Integer offset = 0;
		try {
			offset = Integer.parseInt(req.getParameter("pager.offset"));
		}
		catch (NumberFormatException e) {
		}
		try {
			SystemContext.setPageOffset(offset);
			SystemContext.setPageSize(pageSize);
			// 必须要这个不然文件上传后不会存储
			SystemContext.setRealPath(((HttpServletRequest) req).getSession()
					.getServletContext().getRealPath("/"));
			chain.doFilter(req, resp);
		}
		finally {
			SystemContext.removePageOffset();
			SystemContext.removePageSize();
			SystemContext.removeRealPath();
		}
	}

	@Override
	public void init(FilterConfig cfg) throws ServletException {
		try {
			pageSize = Integer.parseInt(cfg.getInitParameter("pageSize"));
		} catch (NumberFormatException e) {
			pageSize = 15;
		}
	}

}
